<template>
  <div class="layout-padding">
    <el-tabs v-model="activeName" type="border-card" class="card-tabs h-full" @tab-click="handleClick"
      style="width: 100%;height: 100%;">
      <el-tab-pane :label="$t('bar.reprint')" name="first" class="h-full">
        <div class="layout-padding-auto">
          <el-form :model="stateBar.queryForm" ref="queryRef" :inline="true">
            <el-form-item :label="$t('bar.barcodeType')" prop="barcodeType">
              <el-select v-model="stateBar.queryForm.repaetTypeCode" placeholder="Select" style="width: 160px">
                <el-option v-for="item in barcodeTypeOptions" :key="item.value" :label="item.label"
                  :value="item.value" />
              </el-select>
            </el-form-item>
            <el-form-item :label="$t('bar.barcodeStatus')" prop="barcodeStatus">
              <el-select v-model="stateBar.queryForm.barcodeStatus" placeholder="Select" style="width: 160px">
                <el-option v-for="item in barcodeStatusOptions" :key="item.value" :label="item.label"
                  :value="item.value" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-input v-model="stateBar.queryForm.barcode" clearable :placeholder="$t('bar.barcode')" />
            </el-form-item>
            <el-form-item>
              <el-input v-model="stateBar.queryForm.asnno" clearable :placeholder="$t('bar.asnno')" />
            </el-form-item>
            <el-form-item :label="$t('bar.materialcode')" prop="materialCode">
							<MaterialSelect v-model="stateBar.queryForm.materialcode" style="width: 200px">
							</MaterialSelect>
						</el-form-item>
            <el-form-item>
              <el-input v-model="stateBar.queryForm.sourceCode" clearable :placeholder="$t('bar.receiptCode')" />
            </el-form-item>
            <el-form-item :label="$t('bar.warehousename')" prop="warehouseCode">
              <el-select filterable clearable v-model="stateBar.queryForm.warehouseCode" @change="warehouseChange">
                <el-option :key="item.warehouseCode" :label="item.warehouseName" :value="item.warehouseCode"
                  v-for="item in warehousData">
                  <span style="float:left;">{{ item.warehouseName }}</span>
                  <span style="float:left;margin-left: 10px">{{ item.warehouseCode }}</span>
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item :label="$t('bar.locationname')" prop="locationCode">
              <el-select filterable clearable v-model="stateBar.queryForm.locationCode">
                <el-option :key="item.locationCode" :label="item.locationName" :value="item.locationCode"
                  v-for="item in locationData">
                  <span style="float:left;">{{ item.locationName }}</span>
                  <span style="float:left;margin-left: 10px">{{ item.locationCode }}</span>
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item :label="$t('bar.createdate')" prop="createdate">
              <div class="block">
                <el-date-picker v-model="stateBar.queryForm.createdate" clearable type="daterange" unlink-panels
                  range-separator="To" start-placeholder="Start date" end-placeholder="End date"
                  :shortcuts="shortcuts" />
              </div>
            </el-form-item>

            <el-form-item>
              <el-button type="primary" icon="search" plain @click="query">{{
                $t('bar.search')
              }}
              </el-button>
              <el-button type="info" icon="refresh" plain @click="resetQuery">{{ $t('bar.reset') }}</el-button>
              <el-button type="primary" icon="plus" @click="onOpenAddMenu">
                {{ $t('bar.reprint') }}
              </el-button>
              <el-button type="primary" plain icon="View" @click="onOpenQrCode">{{$t('mes.viewQRcode')}}</el-button>
            </el-form-item>
            <hr style="border: 0px;">
            <el-form-item :label="$t('bar.printer')" prop="printer">
              <el-select v-model="PrinterName" placeholder="Select" style="width: 160px">
                <el-option :key="ds.id" :label="ds.value" :value="ds.value" v-for="ds in printerOptions"></el-option>
              </el-select>

              <el-button type="info" plain icon="Printer" @click="print">
                {{ $t('bar.print') }}
              </el-button>
              <el-button type="info" plain icon="Printer" @click="printFinish">
                {{ $t('bar.finishBarcodePrint') }}
              </el-button>
              <el-button type="info" plain icon="Printer" @click="openPrintQr">
                {{ $t('bar.newBarcodePrint') }}
              </el-button>
              <el-button type="info" plain icon="Printer" @click="openPrintQrIron">
                {{ $t('bar.ironBarcodePrint') }}
              </el-button>
              <el-button type="info" plain icon="Printer" @click="openPreview">
                {{$t('bar.previewPrint') }}
              </el-button>
            </el-form-item>
          </el-form>
          <el-table :data="stateBar.dataList" highlight-current-row v-loading="stateBar.loading" border
            style="width: 100%; height: 100%" :cell-style="tableStyle.cellStyle" stripe :summary-method="getSummaries"
            show-summary :header-cell-style="tableStyle.headerCellStyle" ref="tableRef">
            <el-table-column type="selection" width="40" align="center" />
            <el-table-column type="index" label="#" width="80" />
            <el-table-column prop="barcode" :label="$t('bar.barcode')" show-overflow-tooltip width="250" />
            <el-table-column prop="realBarCodeStatus" :label="$t('bar.barcodeStatus')" show-overflow-tooltip
              width="120">
              <template #default="scope">
                <el-tag type="primary" effect="plain">
                  {{ scope.row.realBarCodeStatus }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="barcodeTypeName" :label="$t('bar.barcodetypename')" show-overflow-tooltip
              width="150" />
            <el-table-column prop="materialCode" :label="$t('bar.materialcode')" show-overflow-tooltip width="120" />
            <el-table-column prop="materialName" :label="$t('bar.materialname')" show-overflow-tooltip width="200" />
            <el-table-column prop="initQty" :label="$t('bar.initQty')" show-overflow-tooltip width="100" />
            <el-table-column prop="currentQty" :label="$t('bar.currentqty')" show-overflow-tooltip width="120">
              <template #default="scope">
                <el-tag type="success" effect="plain">
                  {{ scope.row.currentQty }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="unit" :label="$t('bar.unit')" show-overflow-tooltip width="120">
              <template #default="scope">
                <el-tag type="info" effect="plain">
                  {{ scope.row.unit }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="pcsQty" :label="$t('bar.pcsqty')" show-overflow-tooltip />
            <el-table-column prop="processCode" :label="$t('bar.processCode')" show-overflow-tooltip width="100" />
            <el-table-column prop="processName" :label="$t('bar.processName')" show-overflow-tooltip width="100" />
            <el-table-column prop="warehouseCode" :label="$t('bar.warehousecode')" show-overflow-tooltip width="100" />
            <el-table-column prop="warehouseName" :label="$t('bar.warehousename')" show-overflow-tooltip width="120" />
            <el-table-column prop="locationCode" :label="$t('bar.locationcode')" show-overflow-tooltip width="150" />
            <el-table-column prop="locationName" :label="$t('bar.locationname')" show-overflow-tooltip width="200" />
            <el-table-column prop="supplierName" :label="$t('bar.suppliername')" show-overflow-tooltip width="250" />
            <el-table-column prop="asnNo" :label="$t('bar.asnno')" show-overflow-tooltip width="180" />
            <el-table-column prop="sourceCode" :label="$t('bar.receiptCode')" show-overflow-tooltip width="200" />
            <el-table-column prop="productionTime" :label="$t('bar.productionTime')" show-overflow-tooltip
              width="200" />
            <el-table-column prop="productionLineCode" :label="$t('bar.productionLineCode')" show-overflow-tooltip
              width="150" />
            <el-table-column prop="purinStockTime" :label="$t('bar.purinStockTime')" show-overflow-tooltip
              width="200" />
            <el-table-column prop="finishedStocktime" :label="$t('bar.finishedStocktime')" show-overflow-tooltip
              width="200" />
            <el-table-column prop="realQcStatus" :label="$t('bar.qcStatus')" show-overflow-tooltip width="100">
              <template #default="scope">
                <!--根据不同的状态选择不同的颜色的tag-->
                <el-tag
                  :type="scope.row.qcStatus === 'fail' ? 'danger' : changQcstatusNull(scope.row.qcStatus) === 'waitCheck' ? 'info' : 'success'">
                  {{ scope.row.realQcStatus }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="realSecondQcStatus" :label="$t('bar.secondQcStatus')" show-overflow-tooltip
              width="100">
              <template #default="scope">
                <!--根据不同的状态选择不同的颜色的tag-->
                <el-tag
                  :type="scope.row.secondQcStatus === 'fail' ? 'danger' : changQcstatusNull(scope.row.secondQcStatus) === 'waitCheck' ? 'info' : 'success'">
                  {{ scope.row.realSecondQcStatus }}
                </el-tag>
              </template>
            </el-table-column>
          </el-table>

          <pagination @size-change="sizeChangeHandle" @current-change="currentChangeHandle"
            v-bind="stateBar.pagination" />
        </div>
        <MenuDialog @refresh="getDataList" ref="menuDialogRef" />
        <qrCodeDialog ref="qrCodeDialogRef" />
        <printQrDialog ref="printQrDialogref" />
        <printQrIronDialog ref="printQrIronDialogref" />
        <printPreviewDialog ref="printPreviewDialogref" />
      </el-tab-pane>
      <el-tab-pane :label="$t('bar.giftReceiptOrderReprint')" name="second" class="h-full">
        <giftReceiptOrder />
      </el-tab-pane>
      <el-tab-pane :label="$t('bar.ReceiptOrderReprint')" name="third" class="h-full">
        <receiptOrder />
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script setup lang="ts">
import { BasicTableProps, useTable } from '/@/hooks/table';
import { reactive, ref } from 'vue';
import { ElMessage, TabsPaneContext } from 'element-plus';
import { barcodePrint, getPrinter, queryBarcode } from '/@/api/platform/wms/sp';
import { getAllWarehouse, getLocationLists, printQrcode } from '/@/api/platform/wms/reprintbarcode';
import { useI18n } from 'vue-i18n';
import MaterialSelect from "/@/components/mes/select/MaterialSelect.vue";

const { t } = useI18n();
// 引入组件
const MenuDialog = defineAsyncComponent(() => import('./form.vue'));
const qrCodeDialog = defineAsyncComponent(() => import('./qrCode.vue'));
const giftReceiptOrder = defineAsyncComponent(() => import('./giftReceiptOrder.vue'));
const receiptOrder = defineAsyncComponent(() => import('./receiptOrder.vue'));
const printQrDialog = defineAsyncComponent(() => import('./printQrcode.vue'));
const printQrIronDialog = defineAsyncComponent(() => import('./printQrcodeIron.vue'));
const printPreviewDialog = defineAsyncComponent(() => import('./printPreviewDialog.vue'));

const activeName = ref('first');
const locationData = ref<any[]>([]);
const warehousData = ref<any[]>([]);
const getYMD = (date: any) => {
  // 获取年份
  const year = date.getFullYear();

  // 获取月份，注意JavaScript中的月份是从0开始的，因此需要+1
  const month = String(date.getMonth() + 1).padStart(2, '0');

  // 获取日期
  const day = String(date.getDate()).padStart(2, '0');

  // 拼接成 yyyy-MM-dd 格式的字符串
  const formattedDate = `${year}-${month}-${day}`;

  return formattedDate;
};
const today = new Date();
const endDate = new Date(today);
endDate.setDate(today.getDate() - 6); // 今天之后的6天，总共一周
today.setDate(today.getDate() + 1);
const createdate = ref();
// 搜索变量
const queryRef = ref();
const PrinterName = ref('');
const tableRef = ref();
const shortcuts = [
  {
    text: 'Last week',
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
      return [start, end];
    },
  },
  {
    text: 'Last month',
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
      return [start, end];
    },
  },
  {
    text: 'Last 3 months',
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
      return [start, end];
    },
  },
];

//表格的配置
const stateBar: BasicTableProps = reactive<BasicTableProps>({
  queryForm: {
    barcodeTypeCode: ["baseMaterial", "rawMaterials", "finishedProducts", "semiFinishedProducts"],
    createdate: createdate,
    CreateDateStart: createdate.value ? getYMD(createdate.value[0]) : '',
    CreateDateEnd: createdate.value ? getYMD(createdate.value[1]) : ''
  },
  pageList: queryBarcode,
});
//打印机列表
const printerOptions = ref();
// 初始化数据
onMounted(() => {
  getPrinter({ code: "printerSetup", text: "" }).then((res) => {
    printerOptions.value = res.data;
  });
  getWarehouse();
});
// 清空搜索条件
const resetQuery = () => {
  // 清空搜索条件
  queryRef.value?.resetFields();
  //重置打印机
  PrinterName.value = null;
  //重置条码类型
  stateBar.queryForm.repaetTypeCode = null;
  //重置条码
  stateBar.queryForm.barcode = null;
  //重置送货单号
  stateBar.queryForm.asnno = null;
  //重置物料单号
  stateBar.queryForm.materialcode = null;
  stateBar.queryForm.CreateDateStart = createdate.value ? getYMD(createdate.value[0]) : '';
  stateBar.queryForm.CreateDateEnd = createdate.value ? getYMD(createdate.value[1]) : '';
  getDataList(false);
};
const handleClick = (tab: TabsPaneContext, event: Event) => {
  console.log(tab, event)
}

const { tableStyle, getDataList, sizeChangeHandle, currentChangeHandle, downBlobFile } = useTable(stateBar);
const barcodeTypeOptions = ref([
  { label: 'All', value: '' },
  { label: t('bar.NewReprint'), value: 'NewReprint' },
  { label: t('bar.ReceivingForPlay'), value: 'ReceivingForPlay' },
]);
const barcodeStatusOptions = ref([
  { label: 'All', value: '' },
  { label: t('bar.init'), value: 'init' },
  { label: t('bar.inStock'), value: 'inStock' },
  { label: t('bar.checkDel'), value: 'checkDel' },
  { label: t('bar.inputDel'), value: 'inputDel' },
]);
const query = () => {
  stateBar.queryForm.CreateDateStart = createdate.value ? getYMD(createdate.value[0]) : '';
  stateBar.queryForm.CreateDateEnd = createdate.value ? getYMD(createdate.value[1]) : '';
  getDataList();
};
//原材料、半成品标签通用打印
const print = () => {
  var selectedAry = tableRef.value.getSelectionRows();
  if (!PrinterName.value) {
    ElMessage.error(t('bar.selectPrinter'));
    return;
  }
  if (selectedAry.length == 0) {
    ElMessage.error(t('bar.selectBarcodes'));
    return;
  }
  selectedAry.forEach(element => {
    barcodePrint({
      "barcode": element.barcode,
      "printerName": PrinterName.value,
      "operatePage": "ReprintBarcode"
    }).then((res) => {
      if(!res.data.item1){
            ElMessage.error(res.data.item2);
      }
    });
  });

}
const menuDialogRef = ref();
const qrCodeDialogRef = ref();
const printPreviewDialogref = ref();
// 打开新增菜单弹窗
const onOpenAddMenu = (type?: string, row?: any) => {
  menuDialogRef.value.openDialog(type, row);
};
const onOpenQrCode = (type?: string, row?: any) => {
  var selectedAry = tableRef.value.getSelectionRows();
  if (selectedAry.length != 1) {
    ElMessage.error("only select One");
    return
  }
  qrCodeDialogRef.value.openDialog(selectedAry[0]);
};

const printQrDialogref = ref();
//打开新打印条码页面
const openPrintQr = (type?: string, row?: any) => {
  if (!PrinterName.value) {
    ElMessage.error(t('bar.selectPrinter'));
    return;
  }
  printQrDialogref.value.openDialog(PrinterName.value);
};
const printQrIronDialogref = ref();
//打开打印铁托盘页面
const openPrintQrIron = (type?: string, row?: any) => {
  if (!PrinterName.value) {
    ElMessage.error(t('bar.selectPrinter'));
    return;
  }
  printQrIronDialogref.value.openDialog(PrinterName.value);
};
//打印预览
const openPreview = (type?: string, row?: any) => {
  var selectedAry = tableRef.value.getSelectionRows();
  if (selectedAry.length != 1) {
    ElMessage.error("only select One");
    return
  }
  console.log(selectedAry[0],'====');
  printPreviewDialogref.value.openDialog(selectedAry[0]);
};
//打印成品
const printFinish = () => {
  var selectedAry = tableRef.value.getSelectionRows();
  if (!PrinterName.value) {
    ElMessage.error(t('bar.selectPrinter'));
    return;
  }
  if (selectedAry.length == 0) {
    ElMessage.error(t('bar.selectBarcodes'));
    return;
  }
  selectedAry.forEach(async (element) => {
    await printQrcode({
      "qrCode": element.barcode,
      "printerName": PrinterName.value,
      "operatePage": "ReprintBarcode"
    }).then((res) => {
      if(!res.data.item1){
            ElMessage.error(res.data.item2);
      }
    });
  });
}
// 获取仓库
const getWarehouse = () => {
  getAllWarehouse().then((res) => {
    warehousData.value = res.data;
  });
};
//仓库选择加载货位
const warehouseChange = (value) => {
  if (value == null || value == 'undefined') {
    locationData.value = null;
    return;
  }
  stateBar.queryForm.locationCode = null;
  getLocationLists({ "WarehouseCode": value }).then((res) => {
    locationData.value = res.data;
  });
}
const getSummaries = (param) => {
  const { columns, data } = param
  const sums: (string | VNode)[] = []
  columns.forEach((column, index) => {
    if (index === 1) {
      sums[index] = h('div', { style: { textDecoration: 'underline', textAlign: 'center' } }, [
        'Sum',
      ])
      return
    }
    //只要这两行初始数量和当前数量合计
    if (index != 8 && index != 7) return;
    const values = data.map((item) => Number(item[column.property]))
    if (!values.every((value) => Number.isNaN(value))) {
      sums[index] = h('div', { style: { textAlign: 'center' } }, [
        `${values.reduce((prev, curr) => {
          const value = Number(curr)
          if (!Number.isNaN(value)) {
            return Math.round((prev + curr)*10000)/10000
          } else {
            return Math.round(prev*10000)/10000
          }
        }, 0)}`,
      ])
    }
  })

  return sums
}
const changQcstatusNull = (value) => {
  if (value == null)
    return 'waitCheck';
  else
    return value;
}
</script>
<style scoped>
.card-tabs>.el-tabs__content {
  padding: 2px;
}
</style>
